package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.sl.au.entity.Attachment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.sl.au.entity.Device;
import com.sl.au.entity.DeviceInfo;
import com.sl.au.entity.Module;
import com.sl.au.entity.SinglePump;
import com.sl.au.entity.Weekly;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.DeviceService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.SinglePumpService;

@RestController
@RequestMapping(value = "/ui/device")
public class DeviceController extends BaseController {

	private static String MODULE_NAME = "host";// 产品管理--主机

	@Autowired
	DeviceService deviceService;

	@Autowired
	ExcelService excelService;

	@Autowired
	SinglePumpService singlePumpService;

	@Autowired
	AttachmentService attachmentService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Module module = this.getPageModule(DeviceController.MODULE_NAME);
		ModelAndView modelAndView = createLayoutView("device/deviceIndex");
		modelAndView.addObject("module", module);
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Module module = this.getPageModule(DeviceController.MODULE_NAME);
		String dataFilter=module.getDataFilter();
		List<Device> singlePumps = deviceService.getPage(start, length, key, null, null);
		Long count = deviceService.getRepository().getCount(key);
		List<DeviceInfo> devices = new ArrayList<DeviceInfo>();
		for (Device d : singlePumps) {
			if (d != null) {
				String parentId = d.getId();
				List<Attachment> a = attachmentService.getRepository().findByParentId(parentId);
				int num = a.size();
				DeviceInfo info = new DeviceInfo();
				info.setDevice(d);
				info.setId(parentId);
				info.setAttachmentNum(num);
				devices.add(info);
			}
		}
		map.put("data", devices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "getMobilepage", method = RequestMethod.GET)
	public Map<String, Object> getMobilepage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		/*Module module = this.getPageModule(DeviceController.MODULE_NAME);
		String dataFilter=module.getDataFilter();*/
		List<Device> singlePumps = deviceService.getPage(start, length, key, null, null);
		Long count = deviceService.getRepository().getCount(key);
		map.put("data", singlePumps);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 验证设备型号是否存在
	 */
	@RequestMapping(value="/deviceValidate",method=RequestMethod.GET)
	public Map<String,Object>codeValidate(HttpServletRequest request){
		Map<String,Object>map=new HashMap<String,Object>();
		String deviceId=request.getParameter("id");
		String deviceType=request.getParameter("deviceType");
		long count = 0;
		if(deviceId==null||deviceId.equals("")){
			count=deviceService.getRepository().getReCount(deviceType);
		}else{
			List<Device>devices=deviceService.getRepository().findByDeviceType(deviceType);
			if(!devices.isEmpty()){
				if(!devices.get(0).getId().equals(deviceId)){
					count=devices.size();
				}
			}
//			Device device=deviceService.getRepository().findOne(deviceId);
//			System.out.println(!device.getDeviceType().equals(deviceType));
		}
		map.put("code", count);
		return map;
	}

	/**
	 * 添加保存一个主机
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Map<String, Object> saveDevice(HttpServletRequest request, @RequestBody Device device) {
		Map<String, Object> map = new HashMap<String, Object>();
		deviceService.getRepository().save(device);
		List<SinglePump> p = new ArrayList<SinglePump>();
		SinglePump p1 = new SinglePump();
		String type = device.getDeviceType();
		p1.setDevice(device);
		p1.setType(type);
		p1.setSuperior("成套处");
		p.add(p1);
		SinglePump p2 = new SinglePump();
		p2.setDevice(device);
		p2.setType(type);
		p2.setSuperior("外贸处");
		p.add(p2);
		SinglePump p3 = new SinglePump();
		p3.setDevice(device);
		p3.setType(type);
		p3.setSuperior("销售处");
		p.add(p3);
		SinglePump p4 = new SinglePump();
		p4.setDevice(device);
		p4.setType(type);
		p4.setSuperior("售后服务处");
		p.add(p4);
		singlePumpService.getRepository().save(p);
		map.put("code", 0);
		return map;
	}

	/**
	 * 编辑保存一个主机
	 */
	@RequestMapping(method = RequestMethod.PATCH)
	public Map<String, Object> patchWeekly(@RequestBody Device device) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		deviceService.patch(device);

		code = 0;
		map.put("code", code);
		return map;
	}

	/**
	 * EXCEL导入处理 *
	 */
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {

		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		long count = -1;
		String saveFileName = attachmentService.upload(file);
		// 文件传后，再读取EXCEL写入数据库
		if (StringUtils.hasText(saveFileName)) {
			count = deviceService.importExcel(saveFileName);
			code = 0;
		}

		map.put("code", code);
		map.put("count", count);
		return map;
	}

	/**
	 * 删除主机信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/delDevice", method = RequestMethod.GET)
	public Map<String, Object> delDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Device> devices = new ArrayList<Device>();
		for (int i = 0; i < id.length; i++) {
			String deviceId = id[i];
			singlePumpService.getRepository().deleteDevicePrice(deviceId);
			List<Attachment> attachments = new ArrayList<Attachment>();
			attachments = attachmentService.getRepository().findByParentId(deviceId);
			attachmentService.getRepository().deleteInBatch(attachments);
			Device device = new Device();
			device.setId(deviceId);
			devices.add(device);
		}
		deviceService.getRepository().deleteInBatch(devices);
		map.put("code", 0);
		return map;
	}

	/*
	 * 查询导出excel，如果key='', 导出全部
	 */
	@RequestMapping(value = "export/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> excelFile(@PathVariable String key, HttpServletRequest request)
			throws UnsupportedEncodingException {
		if(key.equals("null")) key="";
		List<Device> devices = deviceService.getPage(0, Integer.MAX_VALUE, key, null, null);
		return this.excelService.toExcel(devices, "主机.xlsx");
	}
	///导出选择项
	@RequestMapping(value = "/exportSelects/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
			throws UnsupportedEncodingException {	
		String id[] = key.split(",");
		List<Device> devices = new ArrayList<Device>();
		for (int i = 0; i < id.length; i++) {
			String deviceId = id[i];
			Device d=deviceService.getRepository().findOne(deviceId);
			devices.add(d);
		}
		return this.excelService.toExcel(devices, "主机.xlsx");
	}
	
}
